package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.BookCopy;
import com.example.domain.Book;
import com.example.domain.Bookshelf;
import com.example.domain.Room;
import com.example.domain.Library;
import com.example.dto.BookCopyAddDTO;
import com.example.dto.BookCopyUpdateDTO;
import com.example.mapper.BookCopyMapper;
import com.example.mapper.BookMapper;
import com.example.mapper.BookshelfMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.LibraryMapper;
import com.example.service.BookCopyService;
import com.example.util.Result;
import com.example.vo.BookCopyWithDetailsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 图书副本服务实现类
 */
@Service
public class BookCopyServiceImpl extends ServiceImpl<BookCopyMapper, BookCopy> implements BookCopyService {

    @Autowired
    private BookCopyMapper bookCopyMapper;

    @Autowired
    private BookMapper bookMapper;

    @Autowired
    private BookshelfMapper bookshelfMapper;

    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private LibraryMapper libraryMapper;

    @Override
    @Transactional
    public Result addBookCopy(BookCopyAddDTO bookCopyAddDTO) {
        try {
            // 检查图书是否存在
            Book book = bookMapper.selectById(bookCopyAddDTO.getBookId());
            if (book == null) {
                return Result.error("图书不存在");
            }

            // 创建图书副本
            BookCopy bookCopy = new BookCopy();
            bookCopy.setBookId(bookCopyAddDTO.getBookId());

            boolean success = this.save(bookCopy);
            if (success) {
                return Result.success("图书副本添加成功");
            } else {
                return Result.error("图书副本添加失败");
            }
        } catch (Exception e) {
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    @Override
    public Result getBookCopyById(Long id) {
        try {
            BookCopy bookCopy = this.getById(id);
            if (bookCopy == null) {
                return Result.error("图书副本不存在");
            }
            BookCopyWithDetailsVO vo = buildBookCopyWithDetailsVO(bookCopy);
            return Result.success(vo);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result getBookCopiesByBookId(Long bookId) {
        try {
            QueryWrapper<BookCopy> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_id", bookId);
            List<BookCopy> bookCopies = this.list(queryWrapper);

            List<BookCopyWithDetailsVO> voList = new ArrayList<>();
            for (BookCopy bookCopy : bookCopies) {
                BookCopyWithDetailsVO vo = buildBookCopyWithDetailsVO(bookCopy);
                voList.add(vo);
            }

            return Result.success(voList);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Result updateBookCopyStatus(BookCopyUpdateDTO bookCopyUpdateDTO) {
        try {
            BookCopy bookCopy = this.getById(bookCopyUpdateDTO.getId());
            if (bookCopy == null) {
                return Result.error("图书副本不存在");
            }


            boolean success = this.updateById(bookCopy);
            if (success) {
                return Result.success("状态更新成功");
            } else {
                return Result.error("状态更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    @Override
    public Result getAvailableBookCopies(Long bookId) {
        try {
            QueryWrapper<BookCopy> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("book_id", bookId)
                       .eq("book_copy_status", 0); // 0表示在馆可借阅
            List<BookCopy> bookCopies = this.list(queryWrapper);

            List<BookCopyWithDetailsVO> voList = new ArrayList<>();
            for (BookCopy bookCopy : bookCopies) {
                BookCopyWithDetailsVO vo = buildBookCopyWithDetailsVO(bookCopy);
                voList.add(vo);
            }

            return Result.success(voList);
        } catch (Exception e) {
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    @Override
    public Result deleteBookCopy(Long id) {
        BookCopy bookCopy = this.getById(id);
        if (bookCopy == null) {
            return Result.error("图书副本不存在");
        }
        // 在馆的图书副本才能删除
        if (bookCopy.getBookCopyStatus() != 0) {
            return Result.error("图书副本不在馆，不能删除");
        }
        boolean success = this.removeById(id);
        if (success) {
            return Result.success("图书副本删除成功");
        } else {
            return Result.error("图书副本删除失败");
        }
    }

    /**
     * 构建图书副本详情VO
     */
    private BookCopyWithDetailsVO buildBookCopyWithDetailsVO(BookCopy bookCopy) {
        BookCopyWithDetailsVO vo = new BookCopyWithDetailsVO();
        vo.setId(bookCopy.getId());
        vo.setBookId(bookCopy.getBookId());
        vo.setBookCopyStatus(bookCopy.getBookCopyStatus());


        // 获取图书信息
        Book book = bookMapper.selectById(bookCopy.getBookId());
        if (book != null) {
            vo.setBookTitle(book.getTitle());
            vo.setBookAuthor(book.getAuthor());
        }

        return vo;
    }
}